package com.zt.filter;

import com.zt.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
//@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //把数据转化为http
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求路径
        String requestURI = request.getRequestURI();
        if (requestURI.endsWith("/login")) {
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //获取token
        String token = request.getHeader("token");
        //判断token是否为空
        if (token == null || token.equals("")) {
            //抛出异常
            //设置状态码为401并返回
            response.setStatus(401);
            return;
        }
        //解析token
        try {
            JwtUtils.parseJWT(token).get("username").toString();
        } catch (Exception e) {
            response.setStatus(401);
            return;
        }
        //放行
        filterChain.doFilter(servletRequest, servletResponse);

    }
}
